#coding=utf-8
#author:dn_李四海(qq:653378495)
#动脑学院VIP
'''
主要是练习装饰器,和多线程,多进程的使用

使用装饰器增强完成1-999999所有奇数和计算10次
   1.使用普通方法
   2.使用多线程
   3.使用多进程
   4.采用线程池完成计算
   5.采用进程池完成计算
'''
from multiprocessing import Pool,cpu_count
from multiprocessing.dummy import Pool as threadpool
import time

# 装饰器函数
def c_time(func):
    def inner(num):
        time1=time.time()
        func(num)
        time2=time.time()
        print('计算花费的时间为%s' % str(time2-time1))
    return inner

# 1.使用普通方法
# @c_time
# def c_10time(num):
#     for i in range(10):
#         sum(range(1,num,2))
#
# if __name__=='__main__':
#     c_10time(1000000)  # 计算花费的时间为0.19401097297668457

# 2.使用多线程
# from threading import Thread,current_thread
# def c_10time(num):
#     for i in range(10):
#         sum(range(1,num,2))
#
# @c_time
# def thread_10time(num):
#     for item in range(10):
#         thread=Thread(target=c_time,args=(num,))
#         thread.start()
#         thread.join()
#
# if __name__=='__main__':
#     thread_10time(1000000)  # 计算花费的时间为0.0010004043579101562

# 3.使用多进程
# from multiprocessing import Process,Pool
# def c_10time(num):
#     for i in range(10):
#         sum(range(1,num,2))
#
# @c_time
# def process_10time(num):
#     for item in range(10):
#         pro=Process(target=c_time,args=(num,))
#         pro.start()
#         pro.join()
#
# if __name__=='__main__':
#     process_10time(1000000)  # 计算花费的时间为1.0180583000183105

# 4.采用线程池完成
# 计算
# def c_10time(num):
#     for i in range(10):
#         sum(range(1,num,2))
#
# @c_time
# def thread_10time(num):
#     pools=threadpool(cpu_count())
#     for i in range(10):
#         pools.apply_async(c_10time,(num,))
#     pools.close()
#     pools.join()
#
# if __name__=='__main__':
#     thread_10time(1000000)  # 计算花费的时间为2.006114959716797

# 5.采用进程池完成计算
def c_10time(num):
    for i in range(10):
        sum(range(1,num,2))

@c_time
def process_10time(num):
    pools=Pool(cpu_count())
    for i in range(10):
        pools.apply_async(c_10time,(num,))
    pools.close()
    pools.join()

if __name__=='__main__':
    process_10time(1000000)  # 计算花费的时间为0.8840506076812744